package com.wzapp.sitposture.usercenter.service.impl;

import com.wzapp.sitposture.common.util.BeanUtil;
import com.wzapp.sitposture.easemob.api.impl.EasemobIMUsers;
import com.wzapp.sitposture.usercenter.service.HuanXinService;
import com.wzapp.sitposture.usercenter.view.RegUser;
import com.wzapp.sitposture.usercenter.view.RingAccountDTO;
import io.swagger.client.model.RegisterUsers;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * 功能: ${DESCRIPTION}<br/>
 *
 * @author qianglong
 * @version 1.1
 * @create 2018-12-23 11:32
 **/
@Slf4j
@Service
public class HuanXinServiceImpl implements HuanXinService {

    private EasemobIMUsers easemobIMUsers = new EasemobIMUsers();

    private String PARENT = "_parent";
    private String STUDENT = "_student";

    @Override
    public List<RingAccountDTO> createUser(String userId, String password, String nickname) {
        if(userId == null){
            return null;
        }
        RegisterUsers users = new RegisterUsers();
        RegUser parent = new RegUser();
        parent.setUsername(userId + PARENT);
        parent.setPassword(password);
        parent.setNickname(nickname+"（家长）");
        RegUser student = new RegUser();
        student.setUsername(userId + STUDENT);
        student.setPassword(password);
        student.setNickname(nickname+"（学生）");
        users.add(parent);
        users.add(student);

        Object resultCreate = easemobIMUsers.createNewIMUserSingle(users);
        log.info("=========调用环信注册接口==============" + resultCreate);
        if(resultCreate != null){
            Object resultFriend = easemobIMUsers.addFriendSingle(parent.getUsername(),student.getUsername());
            log.info("=========调用环信添加好友接口=============="+resultFriend);
        }
        List<RingAccountDTO> list = new ArrayList<>(2);
        RingAccountDTO parentDTO = new RingAccountDTO();
        BeanUtil.copyPropertiesIgnoreNull(parent,parentDTO);
        parentDTO.setId(parent.getUsername());
        parentDTO.setType("parent");
        list.add(parentDTO);

        RingAccountDTO studentDTO = new RingAccountDTO();
        BeanUtil.copyPropertiesIgnoreNull(student,studentDTO);
        studentDTO.setId(student.getUsername());
        studentDTO.setType("student");
        list.add(studentDTO);

        return list;
    }

    @Override
    public void deleteRingAccountByUserId(String userId) {

        String parentName = userId + PARENT;
        String studentName = userId + STUDENT;
        easemobIMUsers.deleteIMUserByUserName(parentName);
        easemobIMUsers.deleteIMUserByUserName(studentName);
        easemobIMUsers.deleteFriendSingle(parentName,studentName);
    }
}
